import React from "react";
import style from "./index.module.css";
import { Swiper, Tabs, InfiniteScroll } from "antd-mobile";
import { SearchOutline } from "antd-mobile-icons";
import request from "../../api/request";
import ind from '../../assets/dui03.jpg'
import img1103 from '../../assets/1103.jpg'
import img1203 from '../../assets/1203.jpg'
import img1303 from '../../assets/1303.jpg'
import img1403 from '../../assets/1403.jpg'
const bannerImgs = [
  "http://img.39.net/yp/360/s/498311.jpg",
  "https://img06.zk100.com/upload/product/2020/06/04/931815912606478574.jpg",
  "https://tse2-mm.cn.bing.net/th/id/OIP-C.etLcwO00K9VZ0Ks-lMfrnQHaHa?w=210&h=210&c=7&r=0&o=5&dpr=2&pid=1.7",
  "http://img.39yst.com/uploads/undefined20201027010639417.jpg",
];

const assuranceList = [
  { label: "正品保障" },
  { label: "隐私发货" },
  { label: "专业药师" },
  { label: "官网直供" },
];

const categoryList = [
  { img: "/photo103.jpg", text: "延时持久" },
  { img: "/photo203.jpg", text: "止脱生发" },
  { img: "/photo303.jpg", text: "妇科炎症" },
  { img: "/photo403.jpg", text: "平稳降压" },
  { img: "/img603.jpg", text: "稳控血糖" },
  { img: "/img503.jpg", text: "领券中心" },
  { img: "/img103.jpg", text: "调脂茶" },
  { img: "/img203.jpg", text: "缓解风湿" },
  { img: "/img303.jpg", text: "远离咳喘" },
  { img: "/img403.jpg", text: "全部分类" },
];

// 展示为两行，每行10个，共20个
const gridItems = [...categoryList, ...categoryList];

const brandList = [
  { name: "华领医药", img: img1103 },
  { name: "蓝素", img: img1203 },
  { name: "万全药业", img: img1303 },
  { name: "同仁堂", img: img1403 },
];

type GoodsItem = {
  restorativesid?: number;
  restorativesimage?: string;
  restorativesname?: string;
  restorativesprice?: number;
  [key: string]: unknown; // 允许其他字段
};

function Index() {
  const [activeKey, setActiveKey] = React.useState<string>("精选热销");
  const [goods, setGoods] = React.useState<GoodsItem[]>([]);
  const [allGoodsData, setAllGoodsData] = React.useState<Record<string, GoodsItem[]>>({});
  const requestSeqRef = React.useRef<number>(0);

  type TabData = {
    items: GoodsItem[];
    page: number;
    hasMore: boolean;
    loading: boolean;
    initialized: boolean;
  };
  const [tabData, setTabData] = React.useState<Record<string, TabData>>({});

  const fetchGoods = React.useCallback(async (stateLabel: string) => {
    // 如果是"家庭常备"，使用前三个tab的数据组合
    if (stateLabel === "家庭常备") {
      const combinedData: GoodsItem[] = [];
      
      // 从已缓存的数据中获取前三个tab的数据
      const featuredData = allGoodsData["精选热销"] || [];
      const maleData = allGoodsData["男科用药"] || [];
      const femaleData = allGoodsData["妇科用药"] || [];
      
      // 每个分类取前3个商品，总共9个商品
      combinedData.push(
        ...featuredData.slice(0, 3),
        ...maleData.slice(0, 3), 
        ...femaleData.slice(0, 3)
      );
      
      // 直接展示组合数据（稳定显示）
      setGoods(combinedData);
      setTabData(prev => ({
        ...prev,
        [stateLabel]: {
          items: combinedData,
          page: 1,
          hasMore: false,
          loading: false,
          initialized: true,
        }
      }));
      return;
    }

    try {
      const seq = ++requestSeqRef.current;
      const current = tabData[stateLabel];
      const nextPage = current ? current.page : 1;
      const params: Record<string, unknown> = { pageCode: nextPage, pageSize: 20 };
      if (stateLabel && stateLabel !== "精选热销") {
        params.state = stateLabel;
      }
      const res: { code: number; data: GoodsItem[] } = await request.get(
        "/api/restorative/list",
        { params }
      );
      if (res.code === 200) {
        const data = res.data || [];
        const merged = current ? [...current.items, ...data] : data;
        const hasMore = data.length >= 20;
        if (seq === requestSeqRef.current) {
          setGoods(stateLabel === activeKey ? merged : goods);
        }
        setTabData(prev => ({
          ...prev,
          [stateLabel]: {
            items: merged,
            page: (current ? current.page : 1) + 1,
            hasMore,
            loading: false,
            initialized: true,
          }
        }));
        // 缓存数据供"家庭常备"使用组合
        setAllGoodsData(prev => ({
          ...prev,
          [stateLabel]: merged
        }));
      } else {
        // 非200不清空已有数据，避免闪烁
      }
    } catch (e) {
      // 柔性处理 404/网络错误，避免控制台报错刷屏
      console.warn("获取药品列表失败", stateLabel, e);
      // 异常也不清空已有数据，避免闪烁
    }
  }, [activeKey, goods, tabData, allGoodsData]);

  // 切tab时优先展示缓存/组合数据，保持稳定
  React.useEffect(() => {
    if (activeKey === "家庭常备") {
      const featuredData = allGoodsData["精选热销"] || [];
      const maleData = allGoodsData["男科用药"] || [];
      const femaleData = allGoodsData["妇科用药"] || [];
      const combinedData: GoodsItem[] = [
        ...featuredData.slice(0, 3),
        ...maleData.slice(0, 3),
        ...femaleData.slice(0, 3)
      ];
      if (combinedData.length) setGoods(combinedData);
      return;
    }
    if (tabData[activeKey]?.items?.length) {
      setGoods(tabData[activeKey].items);
      return;
    }
  }, [activeKey, allGoodsData, tabData]);

  // 首次进入某个tab时拉取第一页
  React.useEffect(() => {
    if (activeKey === "家庭常备") return;
    const current = tabData[activeKey];
    // 避免在 loading 状态下重复设置，导致无限循环
    if (current?.initialized || current?.loading) return;
    setTabData(prev => ({
      ...prev,
      [activeKey]: {
        items: prev[activeKey]?.items || [],
        page: prev[activeKey]?.page || 1,
        hasMore: true,
        loading: true,
        initialized: false,
      }
    }));
    fetchGoods(activeKey);
  }, [activeKey, tabData, fetchGoods]);

  // 预取常用tab的第一页，减少后续切换的抖动
  React.useEffect(() => {
    const tabsToPrefetch = ["精选热销", "男科用药", "妇科用药"];
    tabsToPrefetch.forEach(t => {
      if (!tabData[t]?.initialized && !tabData[t]?.loading) {
        setTabData(prev => ({
          ...prev,
          [t]: {
            items: prev[t]?.items || [],
            page: 1,
            hasMore: true,
            loading: true,
            initialized: false,
          }
        }));
        fetchGoods(t);
      }
    });
  }, [fetchGoods, tabData]);

  const loadMore = React.useCallback(async () => {
    if (activeKey === "家庭常备") return;
    // 防抖：若正在加载则跳过
    if (tabData[activeKey]?.loading) return;
    setTabData(prev => ({
      ...prev,
      [activeKey]: {
        items: prev[activeKey]?.items || [],
        page: prev[activeKey]?.page || 1,
        hasMore: prev[activeKey]?.hasMore ?? true,
        loading: true,
        initialized: prev[activeKey]?.initialized ?? false,
      }
    }));
    await fetchGoods(activeKey);
  }, [activeKey, tabData, fetchGoods]);

  const placeholderCards = React.useMemo(() => {
    if (tabData[activeKey]?.initialized) return null;
    const count = 6;
    return Array.from({ length: count }).map((_, idx) => (
      <div className={style.goodsCard} key={`placeholder-${idx}`}>
        <div className={style.goodsImgWrap}>
          <img 
            src={'/photo103.jpg'} 
            alt={'占位图'} 
            loading="lazy"
          />
        </div>
        <div className={style.goodsTitle}>加载中...</div>
        <div className={style.goodsTag}>多盒装</div>
        <div className={style.goodsPrice}>￥0.00</div>
      </div>
    ));
  }, [activeKey, tabData]);

  const TopSection = React.useMemo(() => (
    <>
      <div className={style.bannerWrap}>
        <Swiper autoplay loop>
          {bannerImgs.map((src, i) => (
            <Swiper.Item key={i}>
              <img className={style.bannerImg} src={src} alt={`banner-${i}`} loading="lazy" />
            </Swiper.Item>
          ))}
        </Swiper>
      </div>

      <div className={style.assurance}>
        {assuranceList.map((i, idx) => (
          <div className={style.assuranceItem} key={idx}>
            <span className={style.dot}><img className={style.indimg} src={ind} alt="" loading="lazy" /></span>
            <span>{i.label}</span>
          </div>
        ))}
      </div>

      <div className={style.hGrid}>
        {gridItems.map((i, idx) => (
          <div className={style.hItem} key={idx}>
            <div className={style.hImgWrap}>
              <img src={i.img} alt={i.text} loading="lazy" />
            </div>
            <p>{i.text}</p>
          </div>
        ))}
      </div>

      <div className={style.dots}>
        <span className={`${style.dotLine}`}></span>
        <span className={`${style.dotCircle} ${style.active}`}></span>
      </div>

      <div className={style.sectionTitle}><span>品牌专区</span><span>＞</span></div>
      <div className={style.brandRow}>
        {brandList.map((b, idx) => (
          <div className={style.brandCard} key={idx}>
            <div className={style.brandHeader}>{b.name}</div>
            <div className={style.brandLogoWrap}>
              <img className={style.brandLogo} src={b.img} alt={b.name} loading="lazy" />
            </div>
          </div>
        ))}
      </div>
    </>
  ), []);

  return (
    <div className={style.shopPage}>
      <div className={style.header}>
        <div className={style.title}>妙手商城</div>
        <div className={style.searchBar}>
          <SearchOutline className={style.searchIcon} />
          <input className={style.searchInput} placeholder="米诺地尔搽剂" />
          <button className={style.searchBtn}>搜索</button>
        </div>
      </div>

      {TopSection}

      <div className={style.tabsWrap}>
        <Tabs activeKey={activeKey} onChange={(k) => setActiveKey(k as string)}>
          <Tabs.Tab title="精选热销" key="精选热销" />
          <Tabs.Tab title="男性健康" key="男科用药" />
          <Tabs.Tab title="女性养护" key="妇科用药" />
          <Tabs.Tab title="家庭常备" key="家庭常备" />
        </Tabs>

        <div className={style.goodsGrid}>
          {(!tabData[activeKey]?.initialized && activeKey !== "家庭常备") && placeholderCards}
          {goods.map((g, idx) => (
            <div className={style.goodsCard} key={`${activeKey}-${g.restorativesid ?? idx}`}>
              <div className={style.goodsImgWrap}>
                <img 
                  src={g.restorativesimage || '/photo103.jpg'} 
                  alt={g.restorativesname || '商品图片'} 
                  loading="lazy"
                  onError={(e) => { (e.currentTarget as HTMLImageElement).src = '/photo103.jpg'; }}
                />
              </div>
              <div className={style.goodsTitle}>{g.restorativesname || '商品名称'}</div>
              <div className={style.goodsTag}>多盒装</div>
              <div className={style.goodsPrice}>
                ￥{g.restorativesprice || '0.00'}
              </div>
            </div>
          ))}
        </div>

        {activeKey !== "家庭常备" && (
          <InfiniteScroll 
            loadMore={loadMore} 
            hasMore={tabData[activeKey]?.hasMore ?? true} 
          />
        )}
      </div>

      <a className={style.serviceBtn} href="#">
        <img src="/photo203.jpg" alt="客服" />
        <span>客服</span>
      </a>
    </div>
  );
}

export default Index;
